package com.kizuki.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestLock {

    public static void main(String[] args) {
        BuyTicket1 buyTicket = new BuyTicket1();
        Thread t1 = new Thread(buyTicket, "A1");
        Thread t2 = new Thread(buyTicket, "B1");
        Thread t3 = new Thread(buyTicket, "C1");
        t1.start();
        t2.start();
        t3.start();
    }
}

class BuyTicket1 implements Runnable{
    private int num = 100;
    private boolean flag = true;
    private final Lock l = new ReentrantLock(); // 可重用锁

    @Override
    public void run() {
        while (flag) {
            try {
                /**
                 * 1. lock是可中断锁  l.lockInterruptibly();
                 * 2. lock是非公平锁  l.tryLock(1, TimeUnit.SECONDS)
                 */
                // l.lock();
                System.out.println(Thread.currentThread().getName() + l.tryLock(1, TimeUnit.SECONDS));
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                l.unlock();
            }
        }

    }


    private void buy() {
        if (num > 0) {
            System.out.println(Thread.currentThread().getName() + "获得了第" + num + "张票");
            num --;
        } else {
            flag = false;
        }
    }

}
